//
//  AddCaseController.m
//  QuickCure37
//
//  Created by 马文星 on 16/6/20.
//  Copyright © 2016年 Demos. All rights reserved.
//

#import "AddCaseController.h"
#import "CaseTypeController.h"
#import "CaseTypeDetailController.h"
#import "CaseDTO.h"

@interface AddCaseController () <UITableViewDataSource,UITableViewDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>


@property (nonatomic, strong) UITableView *tableview;

/** 返回的 疾病类型 */
@property (nonatomic, copy) NSString *caseType;

/** 返回的 疾病细分 */
@property (nonatomic, copy) NSString *caseTypeDetail;

///  接收病症描述
@property (nonatomic, strong) UITextView *textview;

///  图片的二进制
@property (nonatomic, strong) NSData *imageData;

//#warning  **************【 上面是能用到的数据 】**********************

@property (nonatomic, strong) UIButton *addImageButton;

/** 图片选择 */
@property (nonatomic, strong) UIImagePickerController *picker;

/** 模型数组 */
@property (nonatomic, strong) NSMutableArray *caseDtoArray;

@end

@implementation AddCaseController

static NSString  *ID = @"CityID";


- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setupUI];
}

- (void)setupUI {
    
    
    self.title = @"增加病例";
    
    //必须要给frame
//    UIButton *rightBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 40, 40)];
//    [rightBtn setTitle:@"提交" forState:UIControlStateNormal];
//    [rightBtn addTarget:self action:@selector(clickRightItem:) forControlEvents:UIControlEventTouchUpInside];
//    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightBtn];
    
    [self addRightButtonItemWithTitle:@"提交" titleColor:BLACK_COLOR];
    
    
    [self.view addSubview:self.tableview];
    
    [self.tableview mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.right.top.bottom.mas_equalTo(0);
        
    }];
    
    
}

#pragma mark  - UITableViewDataSource
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 2;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return 2;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    
    NSInteger section = indexPath.section;
    NSInteger row = indexPath.row;
    
    if (cell==nil) {
        
        if (section==0) {
            
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:ID];
        }else{
            
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
            
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
    }
    
    if (section==0) {
        
        cell.accessoryType  = UITableViewCellAccessoryDisclosureIndicator;
        
        cell.detailTextLabel.text = @"请选择";
        if (row==0) {
            
            cell.textLabel.text = @"疾病类型：";
        }else{
            cell.textLabel.text = @"疾病细分：";
        }
    }else{
        
        //1.
        UILabel *caseDescLab = [[UILabel alloc] init];
        caseDescLab.font = FONT(16);
        [cell.contentView addSubview:caseDescLab];
        
        [caseDescLab mas_makeConstraints:^(MASConstraintMaker *make) {
            
            make.left.top.mas_equalTo(15);
            
        }];
        if (row==0) {
            
            caseDescLab.text = @"病症描述:";
            
            //2.
            UITextView *textview = [[UITextView alloc] init];
            self.textview = textview;
            textview.backgroundColor = [UIColor lightGrayColor];
            textview.font = FONT(15);
            [cell.contentView addSubview:textview];
            
            [textview mas_makeConstraints:^(MASConstraintMaker *make) {
                
                make.left.mas_equalTo(15);
                make.top.mas_equalTo(caseDescLab.mas_bottom).offset(10);
                make.right.mas_equalTo(-15);
                make.bottom.mas_equalTo(-10);
            }];
            
            
        }else{
            
            caseDescLab.text = @"病例照片:";
            
            //3.
            UIButton *addImageButton = [[UIButton alloc] init];
            self.addImageButton = addImageButton;
            [addImageButton setBackgroundImage:[UIImage imageNamed:@"compose_pic_add_highlighted"] forState:UIControlStateNormal];
            [cell.contentView addSubview:addImageButton];
            [addImageButton addTarget:self action:@selector(clickAddImageBtn:) forControlEvents:UIControlEventTouchUpInside];
            
            [addImageButton mas_makeConstraints:^(MASConstraintMaker *make) {
                
                make.left.mas_equalTo(40);
                make.top.mas_equalTo(caseDescLab.mas_bottom).offset(20);
                make.size.mas_equalTo(CGSizeMake(90, 90));
            }];
        }
    }
    
    return cell;
}

#pragma mark  - UITableViewDleegate
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return 0.01;
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    NSInteger section = indexPath.section;
    NSInteger  row    = indexPath.row;
    
    if (section==0) {
        
        UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
        
        if (row == 0) {
            
            CaseTypeController *caseTypeVC = [[CaseTypeController alloc] init];
            
            WEAKSELF
            caseTypeVC.completeBlock = ^(NSString *caseType){
                
                cell.detailTextLabel.text = caseType;
                
                weakSelf.caseType = caseType;
                
            };
            
            [self.navigationController pushViewController:caseTypeVC animated:YES];
            
        }else{
            
            //先要选择疾病类型
            if (self.caseType.length>0) {
                
                CaseTypeDetailController *caseTypeVC = [[CaseTypeDetailController alloc] init];
                
                WEAKSELF
                caseTypeVC.completeBlock = ^(NSString *caseTypeDetail){
                    
                    cell.detailTextLabel.text = caseTypeDetail;
                    
                    weakSelf.caseTypeDetail = caseTypeDetail;
                };
                
                [self.navigationController pushViewController:caseTypeVC animated:YES];
            }else{
            
                [SVPAlertManager alertInfoStatus:@"先要选择疾病类型"];
            }
        }
        
        [tableView deselectRowAtIndexPath:indexPath animated:NO];
        
        
    }
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    NSInteger section = indexPath.section;
    //    NSInteger row = indexPath.row;
    
    if (section == 0) {
        
        return 50;
        
    }else {
        
        return 180;
    }
}


-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    
    [self.view endEditing:YES];
}


#pragma mark  - UIImagePickerDeleget
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    
    
    UIImage *image = info[UIImagePickerControllerOriginalImage];
    
    [self.addImageButton setBackgroundImage:image forState:UIControlStateNormal];
    
    self.imageData = UIImagePNGRepresentation(image);
    
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark  - Actions
/** 添加 右 item */
- (void)clickRightItem:(UIButton *)btn{
    
    
    if (self.caseTypeDetail.length > 0) {
        
        CaseDTO *dto = [[CaseDTO alloc] init];
        
        dto.caseType = self.caseType;
        dto.caseTypeDetail = self.caseTypeDetail;
        
        dto.caseDesc = self.textview.text;
        
        dto.imageData = self.imageData;
    
        NSDateFormatter *df = [[NSDateFormatter alloc] init];
        df.dateFormat = @"yyyy-MM-dd HH:mm:ss";
        dto.timeString  = [df stringFromDate:[NSDate date]];
        
        NSData *dtoData =  [NSKeyedArchiver archivedDataWithRootObject:dto];
        
        [self.caseDtoArray insertObject:dtoData atIndex:0];
        
//        loggerImpt(@"要存的时候有几个数组%ld",self.caseDtoArray.count);
        
        //路径
        NSString *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
        NSString *filePath = [path stringByAppendingPathComponent:@"case.plist"];
        
        if ([self.caseDtoArray writeToFile:filePath atomically:YES]) {
            
            [self.navigationController popViewControllerAnimated:YES];
        }else{
        
            
            [SVPAlertManager alertErrorStatus:@"提交失败"];
        }
        
    }else{
    
        [SVPAlertManager alertInfoStatus:@"请选择具体疾病细分"];
    }
}

/** 添加图片 */
-(void)clickAddImageBtn:(UIButton *)btn{
    
    
    [self presentViewController:self.picker animated:YES completion:nil];
    
}


#pragma mark  - Lazy
- (UITableView *)tableview{
    
    if (_tableview == nil) {
        _tableview = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _tableview.dataSource = self;
        _tableview.delegate = self;
        _tableview.tableFooterView = [UIView new];
        
    }
    return _tableview;
}

-(UIImagePickerController *)picker{
    
    if (_picker == nil) {
        _picker = [[UIImagePickerController alloc] init];
        _picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        _picker.delegate = self;
    }
    return _picker;
}

-(NSMutableArray *)caseDtoArray{
    
    if (_caseDtoArray == nil) {
        
        //路径
        NSString *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
        NSString *filePath = [path stringByAppendingPathComponent:@"case.plist"];
        
        NSArray *arr = [NSArray arrayWithContentsOfFile:filePath];
        
        _caseDtoArray = [[NSMutableArray alloc] initWithArray:arr];
    }
    return _caseDtoArray;
}


@end
